import 'dart:async';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:eh_mobile/common/apis/index.dart';
import 'package:eh_mobile/common/utils/toast/bnw_toast.dart';
import 'package:eh_mobile/common/values/svg_image.dart';
import 'package:eh_mobile/global.dart';
import 'package:eh_mobile/pages/main/homepage/state.dart';
import 'package:eh_mobile/pages/index.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart';
import '../../../common/models/region_list.dart';
import '../../../common/routers/route_names.dart';
import '../../../common/store/user_store.dart';
import '../../../common/utils/enums.dart';
import '../smart_home_info/model/device_dynamic_model.dart';
import 'model/home_device_model.dart';

class HomepageController extends GetxController {
  // 状态管理类
  final state = HomePageState();

  // 中间控制区域
  final centerCardPageController = CarouselController();

  // 底部设备分类区域
  final deviceCategoryPageController = PageController();

  // 设备动态
  final dynamicController = ScrollController();

  // 动画控制器
  late AnimationController scaleAnimationController;

  Timer? _cardTimer;

  Timer? _indicatorTimer;

  String chosePlaceStr = '';
  String chosePlaceViewId = 'chosePlaceViewId'; //首页点击切换地址
  String cardPlaceViewId = 'cardPlaceViewId'; //卡片切换设备地址
  String deviceCategoryWidgetId = 'deviceCategoryWidgetId';
  String smoothPageViewId = 'smoothPageViewId'; //首页底部滑动圆点
  String homeDynamicId = 'homeDynamicId'; //首页底部滑动圆点
  bool isShowCardView = false;
  bool isChoseItemView = true;
  bool isChoseNextItemView = false;

  // 设备动态
  List deviceDynamicList = [];
  RegionListModel model = RegionListModel(
      name: '开关', image: SVGImage.cIcSwitchSvg, selected: false);

  // 快捷面板
  final shortcutList = <Map<String, String>>[
    {'icon': SVGImage.shortcutIcTeslaSvg, 'title': '车'},
    {'icon': SVGImage.shortcutIcRobotvacuumSvg, 'title': '扫地'},
    {'icon': SVGImage.shortcutIcScenarioSvg, 'title': '场景'}
  ];

  // 设备分类
  List deviceCategoryList = [];

  //每页数据
  List get pageList {
    // 计算总页数
    int totalDataCount = deviceCategoryList.length;
    int itemsPerPage = 10;
    int totalPages = (deviceCategoryList.length / 10).ceil();
    // 将数据分配到每页
    List<List> pages = [];
    for (int i = 0; i < totalPages; i++) {
      int startIndex = i * itemsPerPage;
      int endIndex = (i + 1) * itemsPerPage;
      if (endIndex > totalDataCount) {
        endIndex = totalDataCount;
      }
      List pageData = deviceCategoryList.sublist(startIndex, endIndex);
      pages.add(pageData);
    }
    return pages;
  }

  //设备列表
  List deviceSystemList = [];

  DeviceDynamicModelData? dynamicModelData;

  initData() async {
    var result = await HomepageAPI.getMobilePairInfo();
    Logger().d('系统列表$result');
    if (result.isNotEmpty) {
      for (int i = 0; i < result.length; i++) {
        Map element = result[i];
        PairInfoModel infoModel = PairInfoModel.fromJson(element);
        infoModel.index = i;
        infoModel.isChose = i == 0;
        if (i == 0) {
          chosePlaceStr = infoModel.systemInfo?.name ?? '';
        }
        deviceSystemList.add(infoModel);
      }
      update([chosePlaceViewId]);
      PairInfoModel infoModel = PairInfoModel.fromJson(result.first);
      UserStore().userStoreCache.write('userId', infoModel.custom?.userId);
      String mobileIdentity = UserStore().mobileIdentity ?? '';
      Global.websocket
          .connectSocket('eh-api.touchsprite.com/mobile', mobileIdentity)
          .then((value) {
        HomepageAPI.createDataChannel(infoModel.system ?? '').then((res) {
          if (res.keys.contains('statusCode') && res['statusCode'] != 200) {
            BnwToast.showView(Get.context!, infoStr: '服务异常');
          } else {
            String channelId = res['channel_id'];
            List iceServes = res['ice_servers'];
            Global.webRtcChannel.initWebRTC(
                channelId: channelId,
                iceServers: iceServes,
                systemStr: infoModel.system ?? '');
          }
        });
      });

      Global.webRtcChannel.receiveDataBlock = (HomeDeviceModel deviceModel) {
        if (deviceCategoryList.isNotEmpty) {
          deviceCategoryList.clear();
        }
        deviceCategoryList.addAll(deviceModel.data ?? []);
        update([deviceCategoryWidgetId, smoothPageViewId]);
        if (deviceModel.data!.isNotEmpty) {
          UserStore()
              .userStoreCache
              .write('deviceCategoryList', deviceCategoryList);
        }
      };
      Global.webRtcChannel.receiveDynamicBlock = (DeviceDynamicModel res) {
        DeviceDynamicModelData dynamicModelList =
            res.data!.singleWhere((element) => element.type == 'light');
        dynamicModelData = dynamicModelList;
        res.data?.forEach((element) {
          deviceDynamicList.addIf(element.devices!.isNotEmpty, element);
        });
        update([homeDynamicId]);
        if (deviceSystemList.isNotEmpty) {
          UserStore()
              .userStoreCache
              .write('deviceDynamicList', deviceDynamicList);
        }
      };
    } else {
      try {
        Get.offAll(LoginController(), routeName: RouteNames.LOGIN);
      } catch (e) {
        Logger().d('异常$e');
        Get.toNamed(RouteNames.LOGIN);
      }
    }
  }

  /// 点击事件
  void navigatorHomeInfo(DeviceLListType type) {
    // Get.to(const SmartHomeInfoPage(),
    //     fullscreenDialog: true, transition: Transition.downToUp);
  }

  // 设备动态被点击
  void deviceDynamicAction(int index) {
    // Map deviceDynamicMap = deviceDynamicList[index];
    // final deviceName = deviceDynamicMap['title'];
    Get.to(
      SmartHomeInfoPage(),
      fullscreenDialog: true,
      transition: Transition.downToUp,
      arguments: DeviceLListType.light,
    );
  }

  // 快捷面板被点击
  void shortcutAction(int index) {
    // Map shortcutMap = shortcutList[index];
  }

  // 中间控制区域被点击
  void centerCardAction(int index) {
    // Get.to(const SmartHomeInfoPage(),
    //     fullscreenDialog: true, transition: Transition.downToUp);
  }

  // 中间卡片视图被手指触摸开始
  void centerCardTouchDown() {
    if (state.cardTouchDown == false) {
      state.cardTouchDown = true;
      state.centerIndicatorShow = true;
    }

    if (_cardTimer != null) {
      _cardTimer!.cancel();
    }
    if (_indicatorTimer != null) {
      _indicatorTimer!.cancel();
    }
  }

  // 中间卡片视图手指触摸结束
  void centerCardTouchUp() {
    if (_cardTimer != null) {
      _cardTimer!.cancel();
    }
    _cardTimer = Timer(const Duration(seconds: 1), () {
      state.cardTouchDown = false;
    });

    if (_indicatorTimer != null) {
      _indicatorTimer!.cancel();
    }
    _indicatorTimer = Timer(const Duration(milliseconds: 1500), () {
      state.centerIndicatorShow = false;
    });
  }

  //设备分类被点击
  void deviceCategoryAction(HomeDeviceModelData itemData) {
    DeviceLListType deviceLListType = DeviceLListType.light;
    if (itemData.name == '恒温') {
      deviceLListType = DeviceLListType.temp;
    }

    List<HomeDeviceModelDevices>? devices = [];
    var lightList = UserStore().userStoreCache.read('light');
    if (lightList == null || lightList.isEmpty) {
      devices = itemData.devices;
    } else {
      lightList.forEach((element) {
        if (element is Map) {
          devices?.add(HomeDeviceModelDevices.fromJson(element));
        } else {
          devices?.add(element);
        }
      });
    }
    Get.to(
        SmartHomeInfoPage(
          devices: devices,
          itemData: itemData,
          dynamicModelData: dynamicModelData ?? DeviceDynamicModelData(),
          callBackModel: (List res) {
            itemData.devices?.clear();
            for (var element in res) {
              itemData.devices?.add(element);
            }
          },
        ),
        fullscreenDialog: true,
        transition: Transition.downToUp,
        arguments: deviceLListType);
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    if (_cardTimer != null) {
      _cardTimer!.cancel();
    }
    if (_indicatorTimer != null) {
      _indicatorTimer!.cancel();
    }
    super.dispose();
  }
}
